package cn.wolfcode.luowowo.website.web.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeysUtil;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequiredLogin;
import cn.wolfcode.luowowo.website.util.ConstantUtil;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

public class LoginInterceptor implements HandlerInterceptor {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 判断用户是否登录, 如果登录就直接放行, 如果没有登录就判断用户访问的后端控制器是否需要登录
        String token = CookieUtil.getToken(request, ConstantUtil.USER_INFO_TOKEN_COOKIE_NAME);
        if (token != null) {
            UserInfo userInfo = userInfoRedisService.getUserInfoByToken(token);
            if (userInfo != null) {
                // 延长 cookie的过期时间
                CookieUtil.extendCookie(ConstantUtil.USER_INFO_TOKEN_COOKIE_NAME,
                        RedisKeysUtil.USER_LOGIN_TOKEN.getTime().intValue(), response, request);
                // 将用户信息共享session
                request.getSession().setAttribute(ConstantUtil.USER_INFO_IN_SESSION_NAME, userInfo);
                return true;
            }
        }

        // 判断后端控制器是否需要登录
        HandlerMethod method = (HandlerMethod) handler;
        if (!method.hasMethodAnnotation(RequiredLogin.class)) {
            return true;
        }

        // 拿到当前请求的路径
        String path = request.getRequestURL().toString();
        // 以参数的形式拼接到 登录路径上
        response.sendRedirect("/login.html?prePath=" + URLEncoder.encode(path, "utf-8"));
        // 删除保存用户token的cookie
        CookieUtil.deleteCookie(request, ConstantUtil.USER_INFO_TOKEN_COOKIE_NAME);
        return false;
    }
}
